/*
 * Sesame Inc.
 * Copyright (c) 2009 All Rights Reserved.
 */
package com.sesame.controller;

import java.util.*;

import javax.servlet.http.*;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.sesame.domain.Album;
import com.sesame.domain.Image;
import com.sesame.domain.User;
import com.sesame.service.AlbumService;
import com.sesame.service.SearchService;
import com.sesame.toolkit.Encrypt;

/**
 * @author voidman
 * 
 */
public class SearchController extends AbstractController {
    private SearchService searchService;

    public void setSearchService(SearchService searchService) {
        this.searchService = searchService;
    }

    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        String q = request.getParameter("q");
        String type = request.getParameter("type");

        if (q == null) {
            return new ModelAndView("redirect:home.html");

        } else {
            if (q.length() > 20) {
                q = q.substring(0, 20);
            }

            long start_time = System.currentTimeMillis();
            List<Object> objectList = searchService.search(q, type);
            long cost_time = System.currentTimeMillis() - start_time;
            float cost = cost_time / 1000f;
            Map model = new HashMap();
            if (type.equals("user")) {
                List<User> userList = new ArrayList<User>();
                for (int i = 0; i < objectList.size(); i++) {
                    userList.add((User) objectList.get(i));
                }
                model.put("userList", userList);
            } else if (type.equals("album")) {
                Album album = null;
                List<Album> albumList = new ArrayList<Album>();
                for (int i = 0; i < objectList.size(); i++) {
                    album = (Album) objectList.get(i);
                    if (!album.getPrivacy().equals("0"))
                        album.setCover(Encrypt.MapEncrypt("00000/001"));
                    albumList.add(album);
                }
                model.put("albumList", albumList);
            } else if (type.equals("image")) {
                Image image = null;
                List<Image> imageList = new ArrayList<Image>();
                for (int i = 0; i < objectList.size(); i++) {
                    image = (Image) objectList.get(i);
                    if (!image.getPrivacy().equals("0"))
                        image.setUrl(Encrypt.MapEncrypt("00000/001"));
                    imageList.add(image);
                }
                model.put("imageList", imageList);
            } else {

            }

            model.put("q", q);
            model.put("type", type);

            model.put("time", String.valueOf(cost));
            return new ModelAndView("searchResult", model);
        }

    }
}